local pb = require("pb")
local protoc = require("protoc")
local class = reload("class")
local super = reload("super.basic")
local clear = reload("table.opt.clear")

---@class cgzpb:super.basic @使用protobuf
local this = class(super)

function this:ctor(fpaths)
    super.ctor(self)
    self._fpaths = fpaths
end

function this:launch()
    local pc = protoc.new()
    self._pc = pc
    pb.state(nil)
    pb.clear()
    protoc.reload()
    protoc.include_imports = true
    for _, fp in ipairs(self._fpaths) do
        local ok, err = pc:loadfile(fp)
        assert(ok, err)
    end
    pb.option("enum_as_value")
    return self
end

---枚举转lua
function this:enum(name, out)
    local map = clear(out) or {}
    for k, v in pb.fields(name) do
        map[k] = v
    end
    return map
end

function this:encode(name, tab)
    local pack = assert(pb.encode(name, tab))
    return pack
end

function this:decode(name, pack)
    local tab = assert(pb.decode(name, pack))
    return tab
end

return this
